// I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class using DMP (MotionApps v2.0)
// 6/21/2012 by Jeff Rowberg <jeff@rowberg.net>
// Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
//
// Changelog:
//      2013-05-08 - added seamless Fastwire support
//                 - added note about gyro calibration
//      2012-06-21 - added note about Arduino 1.0.1 + Leonardo compatibility error
//      2012-06-20 - improved FIFO overflow handling and simplified read process
//      2012-06-19 - completely rearranged DMP initialization code and simplification
//      2012-06-13 - pull gyro and accel data from FIFO packet instead of reading directly
//      2012-06-09 - fix broken FIFO read sequence and change interrupt detection to RISING
//      2012-06-05 - add gravity-compensated initial reference frame acceleration output
//                 - add 3D math helper file to DMP6 example sketch
//                 - add Euler output and Yaw/Pitch/Roll output formats
//      2012-06-04 - remove accel offset clearing for better results (thanks Sungon Lee)
//      2012-06-01 - fixed gyro sensitivity to be 2000 deg/sec instead of 250
//      2012-05-30 - basic DMP initialization working

/* ============================================
I2Cdev device library code is placed under the MIT license
Copyright (c) 2012 Jeff Rowberg

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
===============================================
*/

// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"

#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu;
MPU6050 accelgyro;
//MPU6050 mpu(0x69); // <-- use for AD0 high


#include <SPI.h>
#include <Mirf.h>
#include <nRF24L01.h>
#include <MirfHardwareSpiDriver.h>


#define OUTPUT_READABLE_QUATERNION
//#define OUTPUT_READABLE_WORLDACCEL


#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
Quaternion q0;          // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector
int const mag = 20;
int const lim = 8;
int const difLim = 14;
struct coor {
		double x;
		double y;
		double z;
		void defineCoorX(){
			x = mag*(1-2*q.y*q.y-2*q.z*q.z);
			y = mag*(2*q.x*q.y + 2*q.z*q.w);
			z = mag*(2*q.x*q.z -2*q.y*q.w);
		}
               
		void defineCoorY(){
			x = mag*(2*q.x*q.y - 2*q.z*q.w);
			y = mag*(1-2*q.x*q.x-2*q.z*q.z);
			z = mag*(2*q.y*q.z +2*q.x*q.w);
		}
		}	xRef,yRef, xRelative;
bool button3_holding_flag,flag_check_stable;
double phixy,phiz;
bool button3_falling_flag,button3_rising_flag;
double bigY_minus, bigY, bigZ_minus, bigZ;    //Save the biggest values of the coor of the gesture
double bigY_abs,bigY_minus_abs;
bool yDir, zDir;    //Save the first direction of gesture on each axis
double LastY, LastZ;
int time,timeBigY,timeBigY_minus,timeBigZ,timeBigZ_minus;
bool mouse_flag;
int16_t ax, ay, az;
int16_t gx, gy, gz;
boolean bflag, eflag;
int mouseSensitivity=90;
bool mouse_myestro_flag;
bool payment_flag;
bool activityTracker_flag;
byte activityTracker_receivedData;

#define PIN_CE	8 //Output
#define PIN_nCS	7 //Output


#define MY_MAC_0	0xEF
#define MY_MAC_1	0xFF
#define MY_MAC_2	0xC0
#define MY_MAC_3	0xAA
#define MY_MAC_4	0x18
#define MY_MAC_5	0x00

static const uint8_t chRf[] = {2, 26,80};
static const uint8_t chLe[] = {37,38,39};
uint8_t i, L, ch = 0;
uint8_t buf[32];
boolean activityTracker_count_flag;
int stepCnt;
long startTime;
long duration;
double avgDuration;
int theChosenMode;
int mouse_buttonReleasedTime, mouse_currentTime, mouse_lastClickedTime;
boolean mouse_clicked_flag;

unsigned char useBluetooth;

// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };



// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}



// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================

void setup() {
    //Setup nRF
    //Mirf.spi = &MirfHardwareSpi;
    //Mirf.init();
    //Mirf.setTADDR((byte *)"recei");
    //Mirf.payload = sizeof(unsigned char);
    //Mirf.config();
    
    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    //Setup P3, P4 and interrupt
    button3_falling_flag=1;
    pinMode(A0,OUTPUT);
    pinMode(A1,OUTPUT);
    pinMode(A2,OUTPUT);
     pinMode(3, INPUT_PULLUP);
     pinMode(4, INPUT_PULLUP);
     attachInterrupt(1, buttonInterrupt, CHANGE);
    // initialize serial communication
    // (115200 chosen because it is required for Teapot Demo output, but it's
    // really up to you depending on your project)
    Serial.begin(115200);
    while (!Serial); // wait for Leonardo enumeration, others continue immediately

    // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3v or Ardunio
    // Pro Mini running at 3.3v, cannot handle this baud rate reliably due to
    // the baud timing being too misaligned with processor ticks. You must use
    // 38400 or slower in these cases, or use some kind of external separate
    // crystal solution for the UART timer.

    // initialize device
    //Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();

    // verify connection
    //Serial.println(F("Testing device connections..."));
    //Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

    // wait for ready
    //Serial.println(F("\nSend any character to begin DMP programming and demo: "));
    //while (Serial.available() && Serial.read()); // empty buffer
    //while (!Serial.available());                 // wait for data
    //while (Serial.available() && Serial.read()); // empty buffer again

    // load and configure the DMP
    //Serial.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();

    // supply your own gyro offsets here, scaled for min sensitivity
    mpu.setXGyroOffset(-8);
    mpu.setYGyroOffset(-22);
    mpu.setZGyroOffset(-49);
    mpu.setZAccelOffset(1078); // 1688 factory default for my test chip

    // make sure it worked (returns 0 if so)
    if (devStatus == 0) {
        // turn on the DMP, now that it's ready
        //Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        //Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        //Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        //Serial.print(F("DMP Initialization failed (code "));
        //Serial.print(devStatus);
        //Serial.println(F(")"));
    }

    // configure LED for output
    setupRF();
    pinMode(LED_PIN, OUTPUT);
    mouse_flag=0;
    activityTracker_flag=1;
    mouse_myestro_flag=1;
    theChosenMode='p';
    digitalWrite(A0,HIGH);
    digitalWrite(A1,HIGH);
    digitalWrite(A2,LOW);
}



// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================

void loop() {
    accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
    // if programming failed, don't try to do anything
    if (!dmpReady) return;

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {
        // other program behavior stuff here
        // .
        // .
        // .
        // if you are really paranoid you can frequently test in between other
        // stuff to see if mpuInterrupt is true, and if so, "break;" from the
        // while() loop to immediately process the MPU data
        // .
        // .
        // .
    }

    // reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    // get current FIFO count
    fifoCount = mpu.getFIFOCount();

    // check for overflow (this should never happen unless our code is too inefficient)
    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
      //  Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
    } else if (mpuIntStatus & 0x02) {
        // wait for correct available data length, should be a VERY short wait
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);
        
        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;
        
        #ifdef OUTPUT_READABLE_QUATERNION
            //=====================================//
            //       Choose mode to work           //
            //  In this mode, we continuously      //
            //  advertise information              //
            //=====================================//
            int serialChar=Serial.read();
            switch(serialChar){
              case 'a':  digitalWrite(A0,LOW);
                         digitalWrite(A1,HIGH);
                         digitalWrite(A2,HIGH);
                         theChosenMode=serialChar;
                         break;
              case 'm':  digitalWrite(A0,HIGH);
                         digitalWrite(A1,LOW);
                         digitalWrite(A2,HIGH);
                         theChosenMode=serialChar;
                         break;
              case 'p':  digitalWrite(A0,HIGH);
                         digitalWrite(A1,HIGH);
                         digitalWrite(A2,LOW);
                         theChosenMode=serialChar;
                         break;
              default:  break;
            }
            switch(theChosenMode){
              case 'a':
                //=====================================//
                //       Activity Tracker Mode         //
                //  In this mode, we continuously      //
                //  advertise information              //
                //=====================================//
                  if(serialChar=='r'){  //reset step counter
                    stepCnt=0;
                  }
                  mpu.dmpGetQuaternion(&q, fifoBuffer);
                  mpu.dmpGetAccel(&aa, fifoBuffer);
                  mpu.dmpGetGravity(&gravity, &q);
                  mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
                  mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
                  // display initial world-frame acceleration, adjusted to remove gravity
                  // and rotated based on known orientation from quaternion
                  stepCount();
                  if(!digitalRead(3)&&!digitalRead(4)&&button3_falling_flag){
                    //activityTracker_flag=0;
                    button3_falling_flag=0;
                    Serial.print(stepCnt);
                  }
                  break;
              case 'm':
                if(!digitalRead(3)&&!digitalRead(4)&&button3_falling_flag){
                  button3_falling_flag=0;
                  mouse_myestro_flag^=mouse_myestro_flag;
                }
                if(!mouse_myestro_flag){
                //==============================//
                //          Mouse Mode          //
                //  Use buttons and raw data    //
                //  to control a mouse.         //
                //==============================//
                mpu.resetFIFO();            //reset FIFO to avoid overflow, out of Gesture mode
                mouse_normalControl();  //Control mouse as normal
                }
                else{
                  //==============================//
                  //          Mouse Mode          //
                  //  Use buttons and raw data    //
                  //  to control a mouse.         //
                  //==============================//
                  mpu.resetFIFO();          //reset FIFO to avoid overflow, out of Gesture mode
                  mouse_myestroControl();   //Determine action by status of buttons: move, click, or scroll
                }
                break;
              case 'p':
                  //==============================//
                  //      Myestro Mouse Mode      //
                  //  Use buttons and raw data    //
                  //  to control a mouse.         //
                  //==============================//
                  //mpu.resetFIFO();          //reset FIFO to avoid overflow, out of Gesture mode
                  //mouse_myestroControl();   //Determine action by status of buttons: move, click, or scroll
                  if(digitalRead(3) && digitalRead(4)){
                    mouse_currentTime=millis();
                    if(az<-17000&&mouse_clicked_flag&&(mouse_currentTime-mouse_buttonReleasedTime)<1000&&(mouse_currentTime-mouse_lastClickedTime)>50){
                      RF_write(251);
                      mouse_clicked_flag=0;
                    }
                    if(az>17000&&!eflag&&(mouse_currentTime-mouse_buttonReleasedTime)<1000&&(mouse_currentTime-mouse_buttonReleasedTime)>200){
                      RF_write(251);
                      mouse_clicked_flag=1;
                      eflag=1;
                      mouse_lastClickedTime=mouse_currentTime;
                    }
                    else if((mouse_currentTime-mouse_buttonReleasedTime)>1000){
                      mouse_clicked_flag=0;
                    }
                  }
                  else if(digitalRead(3) && !digitalRead(4)){
                    mpu.resetFIFO();
                    sendCursorChange();
                    eflag=0;
                    mouse_buttonReleasedTime=millis();
                  }
                //IF 2 buttons are pressed, change to gesture
                  //=====================================//
                  //            Gesture Mode             //
                  //  In this mode, we use Quarternion   //
                  //  to determine gestures              //
                  //=====================================//
                  /*time++;
                  if(button3_holding_flag){
                    mpu.dmpGetQuaternion(&q, fifoBuffer);  //Continuously receive Quaternion values to detect gestures
                    gesture_defineCoor();
                    gesture_checkCoorVertex();
                  }
                  else if(button3_rising_flag){    //The button is released, define the gesture and reset everything
                    gesture_defineGestures();
                    gesture_resetVertexValue();
                    gesture_resetVertexTime();
                    button3_rising_flag=0;
                    //currentArea=0;
                  }*/
                  mpu.dmpGetQuaternion(&q, fifoBuffer);
                  //changeQuaternion();
                  time++;
                  xRef.defineCoorX();
                  yRef.defineCoorY();
                  align_coor();
                  if(button3_holding_flag){
                    //Save the largest coordinates of the gesture
                    if(xRelative.y < bigY_minus){
                      bigY_minus=xRelative.y;  //Save if current y is smaller than the smallest y
                      timeBigY_minus=time;
                      if(bigY<3){
                        yDir=1;                //Direction if toward the right
                      }
                    }
                    else if(xRelative.y > bigY){
                      bigY=xRelative.y;
                      timeBigY=time;
                      if(bigY_minus>-3){
                        yDir=0;
                      }
                    }
                    if(xRelative.z < bigZ_minus){
                      bigZ_minus=xRelative.z;
                      timeBigZ_minus=time;
                      if(bigZ<3){
                        zDir=0;
                      }
                    }
                    else if(xRelative.z > bigZ){
                      bigZ=xRelative.z;
                      timeBigZ=time;
                      if(bigZ_minus>-3){
                        zDir=1;
                      }
                    }
                  }
                  if(!button3_holding_flag && button3_rising_flag){
                    if(bigY-bigY_minus>difLim && bigZ-bigZ_minus>difLim){  //Form a circle, maybe clockwise or anti-clockwise
                      if((timeBigY<timeBigZ_minus&&timeBigZ_minus<timeBigY_minus&&timeBigY_minus<timeBigZ)||(timeBigY<timeBigZ_minus&&timeBigZ_minus<timeBigY_minus&&timeBigZ<timeBigY)||(timeBigY<timeBigZ_minus&&timeBigY_minus<timeBigZ&&timeBigZ<timeBigY)||(timeBigZ_minus<timeBigY_minus&&timeBigY_minus<timeBigZ&&timeBigZ<timeBigY)){
                        RF_write('a');
                        //sendStringTo("Anti-clockwise turned");
                      }
                      else {
                        RF_write('c');
                        //sendStringTo("Clockwise turned");
                      }
                    }
                    else if(bigY-bigY_minus>difLim && bigZ-bigZ_minus<6){  //Form a line horizontally
                      if(abs(bigY)>abs(bigY_minus)){    //To the left
                        RF_write('b');
                        /*if(LastY>10){
                          sendStringTo("Left then stop");
                        }
                        else{
                          sendStringTo("Left then right");
                        }*/
                      }
                      else {    //To the right
                        RF_write('n');
                        /*if(LastY<-10){
                          sendStringTo("Right then stop");
                        }
                        else{
                          sendStringTo("Right then left");
                        }*/
                      }
                    }
                    else if(bigZ-bigZ_minus>10 && bigY-bigY_minus<6){  //Form a line vertically
                      if(abs(bigZ)>abs(bigZ_minus)){    //Down
                        RF_write('u');
                      }
                      else{
                        RF_write('d');
                      }
                        /*if(zDir==0){
                        if(LastZ<-10){
                          sendStringTo("Down then stop");
                        }
                        else{
                          sendStringTo("Down then up");
                        }
                      }
                      else {
                        if(LastZ>10){
                          sendStringTo("Up then stop");
                        }
                        else{
                          sendStringTo("Up then down");
                        }
                      }*/
                    }
                    button3_rising_flag=0;
                    bigZ=0; bigZ_minus=0; bigY=0; bigY_minus=0;
                    time=0;timeBigY=0;timeBigY_minus=0;timeBigZ=0;timeBigZ_minus=0;
                  }
                break;
              default: break;
            }
        #endif
    }
}

void sendStringTo(char* string)
{
  Serial.write(7);
  Serial.println(string);
  Serial.write(6);
} 

void sendStringTo(int string)
{
  Serial.write(7);
  Serial.println(string);
  Serial.write(6);
} 

void sendToChannel(int number, int channel)
{
  Serial.write(channel);
  if (number > 0)
  {
    Serial.print("p");
    Serial.print(number);
  }
  else
  {
    Serial.print("n");
    Serial.print(-number);
  }
  Serial.write(6);
}

void buttonInterrupt(){
  if(!mouse_flag){
   if (digitalRead(3))
   {
     digitalWrite(LED_PIN, LOW);
     button3_holding_flag = false;
     button3_rising_flag = true;
   }
   else
   {
     digitalWrite(LED_PIN, HIGH);
       button3_falling_flag = true;
       button3_holding_flag = true;
       change_coor();
       LastY=xRelative.y;
       LastZ=xRelative.z;
   }
  }
}

void change_coor()
{
  double temp2;
    flag_check_stable = 1; 
    if (xRef.x >=0 )
    {
    phixy =-atan(xRef.y/xRef.x);
    }
    else
    {
      phixy =-atan(xRef.y/xRef.x)- M_PI;
    } 
    temp2 = sqrt(xRef.x*xRef.x + xRef.y*xRef.y);
    phiz = -atan(xRef.z/temp2);
}

void align_coor()
{
  double temp2;
  temp2 = xRef.x  ;
  xRelative.x = temp2 * cos(phixy) - xRef.y*sin(phixy);
  xRelative.y = temp2 * sin(phixy) + xRef.y*cos(phixy);
  temp2 = xRelative.x;
  xRelative.x = temp2 * cos(phiz) - xRef.z*sin(phiz);
  xRelative.z = temp2 * sin(phiz) + xRef.z*cos(phiz);
}

void sendCursorChange(void){
  if (gz > 0)
  {
    RF_write(255);
    RF_write(gz/mouseSensitivity);
  }
  else
  {
    RF_write(254);
    RF_write(-gz/mouseSensitivity);
  }
  
if (gy > 0)
  {
    RF_write(253);
    RF_write(gy/mouseSensitivity);
  }
  else
  {
    RF_write(252);
    RF_write(-gy/mouseSensitivity);
  }
  delay(5);
}

void mouse_normalControl(void){
  if(!digitalRead(3) && digitalRead(4) && bflag==0){
    RF_write('b');  //begin
    bflag=1;
    eflag=0;
  }
  else if(digitalRead(3) && digitalRead(4) && eflag==0){
    RF_write('e');  //end
    eflag=1;
    bflag=0;
  }
  else if(digitalRead(3) && !digitalRead(4)){
    if(gy>0){
      RF_write(243);
      RF_write(gy/100);
    }
    else{
      RF_write(244);
      RF_write(-gy/100);
    }
    delay(5);
  }
  else if(!digitalRead(3) && !digitalRead(4)){
    RF_write('s');
    mouse_flag=0;
  }
  else{
    sendCursorChange();
  }
}

void mouse_myestroControl(void){
  /*if(!digitalRead(3) && digitalRead(4)){
    Serial.write('b');  //begin
    bflag=1;
    eflag=0;
  }
  else if(digitalRead(3) && digitalRead(4) && eflag==0){
    Serial.write('e');  //end
    eflag=1;
    bflag=0;
  }
  else*/ if(digitalRead(3) && digitalRead(4)){
    mpu.resetFIFO();
    mouse_currentTime=millis();
    if(az<-17000&&eflag==0&&(mouse_currentTime-mouse_buttonReleasedTime)<1000&&(mouse_currentTime-mouse_buttonReleasedTime)>200){
      RF_write(251);
      eflag=1;
    }
  }
  else if(digitalRead(3) && !digitalRead(4)){
    sendCursorChange();
    eflag=0;
    mouse_buttonReleasedTime=millis();
  }
  /*else if(!digitalRead(3) && !digitalRead(4)){
    Serial.write('s');
    mouse_flag=0;
  }
  else{
    
  }*/
}

void gesture_checkCoorVertex(void){
  //Save the largest coordinates of the gesture
  if(xRelative.y < bigY_minus){
    bigY_minus=xRelative.y;  //Save if current y is smaller than the smallest y
    RF_write('y');
    RF_write('n');
    RF_write(-bigY_minus);
    timeBigY_minus=time;
  }
  else if(xRelative.y > bigY){
    bigY=xRelative.y;
     RF_write('y');
    RF_write('p');
    RF_write(bigY);
    timeBigY=time;
  }
  if(xRelative.z < bigZ_minus){
    bigZ_minus=xRelative.z;
    timeBigZ_minus=time;
    if(bigZ<3){
      zDir=0;
    }
  }
  else if(xRelative.z > bigZ){
    bigZ=xRelative.z;
    timeBigZ=time;
    if(bigZ_minus>-3){
      zDir=1;
    }
  }
}

void gesture_defineGestures(void){
  if(bigY-bigY_minus>difLim && bigZ-bigZ_minus>difLim){  //Form a circle, maybe clockwise or anti-clockwise
    //mouse_flag=1;
    RF_write('m');
    if((timeBigY<timeBigZ_minus&&timeBigZ_minus<timeBigY_minus&&timeBigY_minus<timeBigZ)||(timeBigY<timeBigZ_minus&&timeBigZ_minus<timeBigY_minus&&timeBigZ<timeBigY)||(timeBigY<timeBigZ_minus&&timeBigY_minus<timeBigZ&&timeBigZ<timeBigY)||(timeBigZ_minus<timeBigY_minus&&timeBigY_minus<timeBigZ&&timeBigZ<timeBigY)){
      RF_write('a');
      //mouse_myestro_flag=0;
      //sendStringTo("Anti-clockwise turned");
    }
    else {
      RF_write('c');
      //mouse_myestro_flag=1;
      //mouse_flag=0;
      //RF_write('s');
      //sendStringTo("Clockwise turned");
    }
  }
  if(bigY-bigY_minus>difLim && bigZ-bigZ_minus<12){  //Form a line horizontally
    bigY_abs=abs(bigY);
    bigY_minus_abs=abs(bigY_minus);
    if(bigY_abs>bigY_minus_abs){    //To the left
      //if(LastY>10){
        //sendStringTo("Left then stop");
        RF_write('n');
        //RF_write(bigY_abs);
        //RF_write('s');
        //RF_write(bigY_minus_abs);
      //}
      //else{
        //sendStringTo("Left then right");
      //}
    }
    else {    //To the right
      //if(LastY<-10){
        //sendStringTo("Right then stop");
        RF_write('b');
        //RF_write(bigY_abs);
        //RF_write('x');
        //RF_write(bigY_minus_abs);
      //}
      //else{
        //sendStringTo("Right then left");
      //}
    }
  }
  else if(bigZ-bigZ_minus>difLim && bigY-bigY_minus<10){  //Form a line vertically
    //activityTracker_flag=1;
    RF_write('a');
    /*if(abs(bigZ)>abs(bigZ_minus)){
      RF_write('z');
      if(LastZ<-10){
        //sendStringTo("Down then stop");
        //RF_write('o');
      }
      else{
        //sendStringTo("Down then up");
      }
    }
    else {
      RF_write('o');
      if(LastZ>10){
        //sendStringTo("Up then stop");
        //RF_write('i');
      }
      else{
        //sendStringTo("Up then down");
      }
    }*/
  }
}

void gesture_defineCoor(void){
  xRef.defineCoorX();
  yRef.defineCoorY();
  align_coor();
}

void gesture_resetVertexValue(void){
  bigZ=0; 
  bigZ_minus=0;
  bigY=0; 
  bigY_minus=0;
  bigY_abs=0;
  bigY_minus_abs=0;
}

void gesture_resetVertexTime(void){
  time=0;
  timeBigY=0;
  timeBigY_minus=0;
  timeBigZ=0;
  timeBigZ_minus=0;
}

void setupRF(void)
{
  Mirf.spi = &MirfHardwareSpi;  
  Mirf.init();
  Mirf.setTADDR((byte *)"clie1");
  Mirf.setRADDR((byte *)"serv1");
  Mirf.payload = sizeof(unsigned char);
  Mirf.config();
}

void RF_write(unsigned char thisByte)
{
  Mirf.send(&thisByte);
  while(Mirf.isSending());
}

void stepCount(void){
  if(aaWorld.z>6000&&activityTracker_count_flag){
    stepCnt++;
    duration=millis()-startTime;
    if(stepCnt>1&&duration<3000){
      avgDuration=(avgDuration*(stepCnt-1)+duration)/stepCnt;
    }
    if(duration>avgDuration*2){
      stepCnt++;
    }
    startTime=millis();
    activityTracker_count_flag=0;
  }
  else if(aaWorld.z<0){
    activityTracker_count_flag=1;
  }
}

void runAnalyze(void){
  if(avgDuration>370&&avgDuration<500){
    RF_write('R');
    RF_write('N');
  }
  else if(avgDuration>270&&avgDuration<370){
    RF_write('R');
    RF_write('F');
  }
  else if(avgDuration>500){
    RF_write('J');
  }
  else if(avgDuration<270){
    RF_write('F');
  }
}
